<?php
/* ******************************
 *	Recipie aJax actions
 * ******************************
 */
 
include('../../includes/classes/core.php');
include('../../includes/classes/category.tree.class.php');
include('../../includes/classes/log.class.php');

$log 		= new log();

$action = $_REQUEST['act'];
$error	= '';
$data	= '';


switch ($action) {
    case 'get_add_page':
		$page		= GetPage();
		$data		= array('page'	=> $page);
		
        break;
    case 'get_edit_page':
	    $rec_id		= $_REQUEST['id'];
		$page		= GetPage(GetRecipie($rec_id));
        
        $data 		= array('page'	=> $page);
        
        break; 
        
    case 'get_local_id':
        
        $data = array('local_id' => GetLocalID() );
        
        break;
        	
    case 'get_list':
	    $count = $_REQUEST['count'];
	    $hidden = $_REQUEST['hidden'];
	    
	    
	    $rResult = mysql_query("SELECT  production.`id`,      
										`production`.`name`,
										ROUND(SUM((SELECT DISTINCT reserve.price FROM reserve WHERE reserve.production_id = rec.ingredient_id ) * rec.quantity * rec.default_amount),4)  AS `self_price`       
										FROM         `recipie` AS rec 
										LEFT JOIN `production` ON `production`.`id` = `rec`.`recipie_id`
										WHERE `production`.`id` IN (SELECT `recipie_id` FROM `recipie`) AND `production`.`actived` = 1
										GROUP BY     rec.recipie_id");
		
		$data = array(
			"aaData"	=> array()
		);
		
		if(!$rResult){
			$error = 'Invalid query: ' . mysql_error();
		}else{
			while ( $aRow = mysql_fetch_array( $rResult ) )
			{
				$row = array();
				for ( $i = 0 ; $i < $count ; $i++ )
				{
					/* General output */
					$row[] = $aRow[$i];
					if($i == ($count - 1)){
						$row[] = '<input type="checkbox" name="check_' . $aRow[$hidden] . '" class="check" value="' . $aRow[$hidden] . '" />';
					}
				}
				$data['aaData'][] = $row;
			}
			
		}
		
        break;
    case 'save_rec':
		$id 				= $_REQUEST['l_id'];
		$user_id			= $_COOKIE['USERID'];	
    	$code	 			= $_REQUEST['code'];
    	$name				= $_REQUEST['name'];
    	$pos_menu_category	= $_REQUEST['cat'];
    	$unit				= $_REQUEST['un'];
    	$image              = $_REQUEST['img'];
    	$rec_id				= $_REQUEST['rec_id'];

		
		/*if(CheckRecipieExist($id)){
				AddRecipie($id, $user_id, $code, $name, $pos_menu_category, $unit, $image);
			} else {
				SaveRecipie($id, $user_id, $code, $name, $pos_menu_category, $unit);
			}
		*/
		if($rec_id == '')
    		if(!CheckRecipieExist($name)){
    			if(!CheckRecipieCode($code)){
    				AddRecipie($id, $user_id, $code, $name, $pos_menu_category, $unit, $image);
    				
    				GLOBAL $log;
    				$log->setInsertLog('production');
    			} else {
    				$error = 'პროდუქტი ასეთი კოდით უკვე არის სიაში!';
    			}
    		} else {
    			$error = '"' . $name . '" უკვე არის სიაში!';
    		}
    	else {
    		SaveRecipie($id, $user_id, $code, $name, $pos_menu_category, $unit, $image);
    		}  	
		
        break;
        
    case 'disable':
		$rec_id	= $_REQUEST['id'];
		DeleteRecipie($rec_id);
		
        break;
	case 'check_prod_list':
		$l_id 		= $_REQUEST['id'];
		$check			= ChackProdList($l_id);
		if(!$check){
			$error = 'შემადგენლობის სია ცარიელია!';
		}

        break;

    case 'clear_db':
		ClearDB();
		
        break;
    default:
       $error = 'Action is Null';
}

$data['error'] = $error;

echo json_encode($data);


/* ******************************
 *	Recipie Functions
 * ******************************
 */

function CheckRecipieCode($code){
	
	$res = mysql_fetch_assoc(mysql_query("SELECT `code`
			FROM `production`
			WHERE `production`.`code` = '$code'"));
	if($res['code'] != ''){
		return true;
	}
	return false;
	
	
}

function GetLocalID()
{
	GLOBAL $db;
	$id = $db->increment('production');
	return $id;
}

function ClearDB()
{
	$req = mysql_query("SELECT `id`
						FROM `recipie_detail`
						WHERE `recipie_id` NOT IN (SELECT `id` FROM `recipie`)");

	while( $res = mysql_fetch_assoc($req)){
		mysql_query("DELETE
					 FROM
						`recipie_detail`
					 WHERE
						`id` = $res[id]");
	}
}

function AddRecipie($id, $user_id, $code, $name, $pos_menu_category, $unit, $image)
{
	mysql_query("INSERT INTO production (id, user_id, code, name, category, pos_menu_category, unit, image)
  					VALUES   ($id, $user_id, $code, '$name', 1, $pos_menu_category, $unit, '$image')");
}

function SaveRecipie($id, $user_id, $code, $name, $pos_menu_category, $unit, $image) 
{
	mysql_query("UPDATE
	    			`production`
				 SET
					`user_id`   		= $user_id,
					`code`	 			= '$code',
					`name`				= '$name',
					`pos_menu_category` = $pos_menu_category,
					`image`				= '$image',
					`unit` 				= $unit
				 WHERE
					`id` = $id");
}

function DeleteRecipie($rec_id)
{
    mysql_query("UPDATE 	
	    			`recipie`
	    		 SET
	    		 	`actived` 	=  0
				 WHERE
					`recipie_id` = $rec_id ");
					
    mysql_query("UPDATE  
	    			`production`
	    		 SET
	    		    `actived`  = 0
				 WHERE
					`id` = $rec_id ");
}


function ChackProdList($l_id)
{
	$check = false;
	$req = mysql_query("SELECT `recipie_id`
						FROM `recipie`
						WHERE `recipie_id` = $l_id");

	if (mysql_num_rows($req) > 0){
		$check = true;
	} 

	return $check;
}

function CheckRecipieExist($name) 
{
    $res = mysql_fetch_assoc(mysql_query("SELECT `name`
										  FROM `production`
										  WHERE `name` = '$name'"));
	if($res['name'] != ''){
		return true;
	}
	return false;
}

function GetSize($point)
{
	$data = '';
	$req = mysql_query("SELECT `id`, `name`
						FROM `production_unit`");

	if($point == ''){
		$data = '<option value="0" selected="selected"></option>';
	}

	while( $res = mysql_fetch_assoc($req)){
		if($res['id'] == $point){
			$data .= '<option value="' . $res['id'] . '" selected="selected">' . $res['name'] . '</option>';
		} else {
			$data .= '<option value="' . $res['id'] . '">' . $res['name'] . '</option>';
		}
	}

	return $data;
}

function GetCategory($point)
{
	$data = '';

	$data = '<option value="0" selected="selected"></option>';
	$tree = new CategoryTree($point);
	$data .= $tree->GetData();

	return $data;
}

function GetRecipie($rec_id) 
{
    $res = mysql_fetch_assoc(mysql_query("SELECT 	`id`,
    												`code`,
    												`name`,    											 	
    												`pos_menu_category`,
													`unit`,
    												`image`,
    												`comment`
    												FROM 		`production`
									      WHERE 	`id` = $rec_id"));
	return $res;
}

function GetPage($res = '')
{
	$image = $res[image];
	if(empty($image)){
		$image = '0.jpg';
	}
	
	$data = '
	<!-- jQuery Dialog -->
    <div id="add-edit-prod-form-field" title="შემადგენლობა">
    	<!-- aJax -->
	</div>
	<div id="dialog-form">
		<fieldset style="width: 300px; float: left;">
	    	<legend>ძირითადი ინფორმაცია</legend>

	    	<table class="dialog-form-table">
	    		<tr>
					<td style="width: 170px;"><label for="code">კოდი</label></td>
					<td>
						<input type="text" id="code" class="idle" onblur="this.className=\'idle\'" onfocus="this.className=\'activeField\'" value="' . $res['code'] . '" />
					</td>
				</tr>								
				<tr>
					<td style="width: 170px;"><label for="name">დასახელება</label></td>
					<td>
						<input type="text" id="name" class="idle" onblur="this.className=\'idle\'" onfocus="this.className=\'activeField\'" value="' . $res['name'] . '" />
					</td>
				</tr>

																
				<tr>
					<td style="width: 170px;"><label for="category">კატეგორია</label></td>
					<td>
						<select id="category" class="idls">' . GetCategory($res[pos_menu_category]) . '</select>
					</td>
				</tr>
				<tr>
					<td style="width: 170px;"><label for="unit">ზომის ერთეული</label></td>
					<td>
						<select id="unit" class="idls num" style = " width: 165px !important;">' . GetSize($res[unit]) . '</select>
					</td>
				</tr>
				<tr>
					<td style="width: 170px;"><label for="unit">შენიშვნა</label></td>
					<td>
						<textarea id="comment" class="idle large" cols="30" rows="1" style="width:159px !important; height:50px !important;">' . $res['comment'] . '</textarea>
					</td>
				</tr>
			</table>
        </fieldset>
							
		<fieldset style="width: 300px; float: left; margin-left:6px !important; height:190px !important;">
	    	<legend>პროდუქტის სურათი</legend>
			
	    	<table class="dialog-form-table" width="100%">
	    		<tr>
					<td id="img_colum" colspan="2">
						<img id="upload_img" src="media/uploads/images/production/' . $image . '">
					</td>
				</tr>
				<tr><!-- Upload Image -->
					<td id="act">
						<span>
							<a href="#" id="view_image" class="complate" style="float:left; margin-left:14px;">View</a> <p style="float:left; margin-left:5px;">|</p> <a href="#" id="delete_image" class="delete" style="float:left; margin-left:5px;">Delete</a>
						</span>
					</td>
					<td>
						<div class="file-uploader">
							<input id="choose_file" type="file" name="choose_file" class="input" style="display: none;">
							<button id="choose_button" class="center">აირჩიეთ ფაილი</button>
						</div>
					</td>
				</tr>
			</table>
        </fieldset>	

		
								
		<fieldset>
	    	<legend>პროდუქტი</legend>

		    <div class="inner-table">
			    <div id="dt_example" class="ex_highlight_row">
			        <div id="container" class="overhead_container">
			        	<div id="button_area">
			        		<button id="add_button_prod">დამატება</button><button id="delete_button_prod">წაშლა</button>
			        	</div>
			            <div id="dynamic">
			                <table class="display" id="prod_list">
			                    <thead>
			                        <tr id="datatable_header">				                        
			                            <th>ID</th>
			                            <th style="width : 100%">პროდუქტი</th>
			                            <th class="min" style="width:90px !important;">რაოდენობა</th>
										<th class="min" style="width:100px !important;">თვითღირებ.</th>
										<th class="min" style="width:90px !important;">ნამ. ფასი</th>
			                            <th class="check">#</th>
			                        </tr>
			                    </thead>
			                    <thead>
			                        <tr class="search_header">				                        
			                            <th class="colum_hidden">
			                            	<input type="text" name="search_id" value="ფილტრი" class="search_init" />
			                            </th>
			                            <th>
			                            	<input type="text" name="search_prod" value="ფილტრი" class="search_init" />
			                            </th>
			                            <th></th>
										<th></th>
										<th></th>
										<th>
											<input type="checkbox" name="check-all" id="check-all-prod" style="margin-left: 13px;">
										</th>
			                        </tr>
			                    </thead>
			                </table>
			            </div>
			        </div>
			    </div>
			</div>
		</fieldset>
								
			
								
								
		<!-- ID -->
		<input type="hidden" id="rec_id" value="' . $res['id'] . '" />
		<input type="hidden" id="local_rec_id"/>
    </div>    
    ';
    
	return $data;
}
?>